<template>
  <div>
    <el-button type="primary" @click="dialogVisible = true">新增用户</el-button>
    <el-button type="primary" @click="showPermissionDialog = true">调整用户管理权</el-button>
    <el-table :data="users" style="width: 100%; margin-top: 20px">
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="昵称" prop="name"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column
        label="管理员"
        prop="permission"
        :formatter="formatAdmin"
      ></el-table-column>
      <el-table-column label="最近登录" prop="lastLoginTime"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            @click="handleResetPassword(row.id)"
            type="text"
            size="small"
            :disabled="false"
            >重置密码</el-button
          >
          <el-button
            @click="handleDeleteUser(row.id)"
            type="text"
            size="small"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加用户"
      width="50%"
      :before-close="handleClose"
    >
      <el-form :model="newUser">
        <el-form-item label="用户名" required>
          <el-input v-model="newUser.username"></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="newUser.name"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="newUser.email"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="newUser.password"></el-input>
        </el-form-item>
        <el-form-item label="管理员权限">
          <el-switch v-model="newUser.permission"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddUser">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 调整用户权限对话框 -->
    <el-dialog
      v-model="showPermissionDialog"
      title="调整用户权限"
      width="50%"
      :before-close="handleClosePermissionDialog"
    >
      <el-form :model="userPermission">
        <el-form-item label="用户名" required>
          <el-input v-model="userPermission.username"></el-input>
        </el-form-item>
        <el-form-item label="权限等级" required>
          <el-input v-model="userPermission.permission"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelPermissionAdjustment">取 消</el-button>
        <el-button type="primary" @click="updateUserPermission">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      users: [], // 用户数据
      dialogVisible: false, // 控制添加用户对话框显示
      showPermissionDialog: false, // 控制权限调整对话框显示
      newUser: {
        username: "",
        name: "",
        email: "",
        password: "888888",
        permission: false,
      },
      userPermission: {
        username: "",
        permission: "",
      },
    };
  },
  created() {
    this.fetchUsers();
  },
  methods: {
    // 获取用户数据
    async fetchUsers() {
      try {
        const res = await request.get("/user/selectAll");
        this.users = res.data;
      } catch (error) {
        console.error("获取用户数据失败:");
      }
    },

    // 添加用户
    async addUser() {
      if (this.newUser.permission) {
        this.newUser.permission = "1";
      } else {
        this.newUser.permission = "0";
      }
      if (this.newUser.name === "") {
        this.newUser.name = this.newUser.username;
      }

      try {
        const res = await request.post("/register", this.newUser);
        if (res.code === "200") {
          this.dialogVisible = false;
          this.fetchUsers();
          this.newUser = {
            username: "",
            name: "",
            email: "",
            password: "888888",
            permission: false,
          };
        } else {
          window.alert(res.msg);
        }
      } catch (error) {
        console.error("请求失败:");
      }
    },

    // 取消添加用户
    cancelAddUser() {
      this.dialogVisible = false;
      this.newUser = {
        username: "",
        name: "",
        email: "",
        password: "888888",
        permission: false,
      };
    },

    // 确认重置密码
    handleResetPassword(userId) {
      this.$confirm("确认重置该用户的密码吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await request.put(`/user/resetPossword/${userId}`);
          if (res.code === "200") {
            this.$message.success("重置成功");
          } else {
            console.error("重置密码失败");
          }
        })
        .catch(() => {
          this.$message.info("取消重置密码");
        });
    },

    // 确认删除用户
    handleDeleteUser(userId) {
      this.$confirm("确认删除该用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await request.delete(`/user/delete/${userId}`);
          if (res.code === "200") {
            this.fetchUsers();
            this.$message.success("删除成功");
          } else {
            console.error("删除用户失败");
          }
        })
        .catch(() => {
          this.$message.info("取消删除用户");
        });
    },

    // 格式化管理员字段
    formatAdmin(data) {
      return data.permission === "1" ? "是" : "否";
    },

    // 取消权限调整对话框
    cancelPermissionAdjustment() {
      this.showPermissionDialog = false;
      this.userPermission = {
        username: "",
        permission: "",
      };
    },

    // 更新用户权限
    async updateUserPermission() {
      const { username, permission } = this.userPermission;
      try {
        const res = await request.put(`/user/updateUserPermission/${username}/${permission}`);
        if (res.code === "200") {
          this.showPermissionDialog = false;
          this.fetchUsers();
          this.$message.success("权限更新成功");
        } else {
          this.$message.error("权限更新失败");
        }
      } catch (error) {
        console.error("更新权限失败:", error);
      }
    },

    // 关闭权限调整对话框
    handleClosePermissionDialog() {
      this.showPermissionDialog = false;
      this.userPermission = {
        username: "",
        permission: "",
      };
    },
  },
};
</script>
